<template>
    <div class="budgetTabelPagePage">
        <div class="search-wrap d-flex a-center">
            <div class="search-item d-flex a-center">
                <label>部门</label>
                <el-select v-model="form.departmentId" class="m-l5" placeholder="请选择部门" clearable>
                    <el-option v-for="(item,index) in departmentList" :key="index" :label="item.deptName" :value="item.deptId"></el-option>
                </el-select>
            </div>
            <div class="search-item d-flex a-center m-l20">
                <label>项目名称</label>
                <el-select v-model="form.projectId" class="m-l5" placeholder="请选择项目" clearable>
                    <el-option v-for="(item,index) in projectList" :key="index" :label="item.projectName" :value="item.projectId"></el-option>
                </el-select>
            </div>
            <div class="search-item d-flex a-center m-l20">
                <label>年度</label>
                <el-date-picker
                        class="m-l10"
                        clearable
                        v-model="form.year"
                        value-format="YYYY"
                        size="large"
                        type="year"
                        placeholder="请选择"
                />
            </div>
            <div class="search-item d-flex a-center m-l20">
                <label>季度</label>
                <el-select class="m-l10" v-model="form.quarter" clearable>
                    <el-option label="第一季度" value="1"></el-option>
                    <el-option label="第二季度" value="2"></el-option>
                    <el-option label="第三季度" value="3"></el-option>
                    <el-option label="第四季度" value="4"></el-option>
                </el-select>
            </div>
            <div class="search-buttons m-l50 d-flex a-center">
                <el-button
                        color="#fc702b"
                        style="color:#fff;"
                        @click.prevent="onQuery"
                >查询</el-button>
                <el-button
                        color="#f0f0f0"
                        style="color: #000000"
                        @click.prevent="onReset"
                >重置</el-button>
                <el-divider direction="vertical" />
                <el-button
                        style="color:#FC7018;background: #FFFFFF;"
                        @click="onExport"
                >
                    <svg-icon icon-class="project-detail-icon-derive" class="icon-export m-r5"></svg-icon>
                    一键导出
                </el-button>
            </div>
        </div>
        <public-table
                class="m-t20"
                index
                :indexWidth="'100'"
                :page="page"
                :tableData="tableData"
                :tableOption.sync="tableOption"
                @page-change="onPageChange"
                @handleSelectionChange="handleSelectionChange"
        >
            <template #cost="scope">
                <span v-if="!scope.row.isEdit">{{scope.row.cost}}</span>
                <el-input v-else v-model="scope.row.cost" placeholder="请输入"></el-input>
            </template>
            <template #income="scope">
                <span v-if="!scope.row.isEdit">{{scope.row.income}}</span>
                <el-input v-else v-model="scope.row.income" placeholder="请输入"></el-input>
            </template>
            <template #fee="scope">
                <span v-if="!scope.row.isEdit">{{scope.row.fee}}</span>
                <el-input v-else v-model="scope.row.fee" placeholder="请输入"></el-input>
            </template>
            <template #profit="scope">
                <span v-if="!scope.row.isEdit">{{scope.row.profit}}</span>
                <el-input v-else v-model="scope.row.profit" placeholder="请输入"></el-input>
            </template>
            <template #update="scope">
                <el-button
                        v-if="!scope.row.isEdit"
                        color="#fff"
                        style="border: 1px solid #fc7037;color: #fc7037;"
                        @click="onEdit(scope.row)"
                >编辑</el-button>
                <div v-else>
                    <el-button    color="#fc702b"
                                  style="color:#fff;"
                                  @click="onSave(scope.row)"
                    >保存</el-button>
                    <el-button     color="#f0f0f0"
                                   style="color: #000000"
                                   @click="onCancel(scope.row)"
                    >取消</el-button>
                </div>
            </template>
        </public-table>
    </div>
</template>

<script setup>
import {budgetManagement, exportApi, fundManagementApi} from "@/api/businessFinance";
import {onMounted, reactive, ref} from "vue";
import {
    ElSelect,
    ElOption,
    ElDatePicker,
    ElForm,
    ElFormItem,
    ElTable,
    ElTableColumn,
    ElCascader,
    ElMessage,
    ElRow,
    ElCol,
    ElDivider
} from "element-plus";
import PublicTable from "@/components/PublicTable.vue";
import {exportExcelFile, resetForm} from "@/common/utils/GlobalUtils";
import PublicDialog from "@/components/PublicDialog.vue";

const page = reactive({
    total: 0,
    current: 1,
    size: 10
});

const tableData = ref([]);

const tableOption = ref([
    { label: "部门名称", prop: "departmentName" },
    { label: "项目名称 ", prop: "projectName" },
    { label: "年度 ", prop: "year" },
    { label: "季度 ", prop: "quarter" },
    { label: "成本预测金额 ", prop: "cost",width: 120,slot: true },
    { label: "收入预测金额 ", prop: "income",width: 120,slot: true },
    { label: "费用预测金额 ", prop: "fee",width: 120,slot: true },
    { label: "收益预测金额 ", prop: "profit",width: 120,slot: true },
    { label: "利润预测金额 ", prop: "earnings", width: 120 },
    {label: '操作',prop: 'update',slot:true,width: 200,fixed:'right'}
]);

const form = reactive({
    departmentId:'',
    projectId:'',
    year:'',
    quarter:''
});

// 新增预算的form
const budgetForm = reactive({
    departmentId:'',
    projectId:'',
    year:'',
    quarter:'',
    list:[]
});


const departmentList = ref([]);
const getDepartmentVo = () => {
    fundManagementApi.getDepartmentVo().then(res=>{
        departmentList.value = res.data;
    });
}

const projectList = ref([]);
const getProjectList = () => {
    budgetManagement.getProjectList().then(res=>{
        projectList.value = res.data;
    });
}

const getBudgetPredictionRecordInfoList = (param) => {
    budgetManagement.getBudgetPredictionRecordInfoList(param).then(res=>{
        res.data.content.forEach(item=>{
            item.isEdit = false;
        });
        tableData.value = res.data.content;
        page.total = res.data.totalSize;
    });
}

const onQuery = () => {
    page.current = 1;
    page.size = 10;
    let param = {
        param: {
            ...form
        },
        pageNum: page.current,
        pageSize: page.size
    };
    getBudgetPredictionRecordInfoList(param);
}

const onReset = () => {
    resetForm(form);
    page.current = 1;
    page.size = 10;
    let param = {
        pageNum: page.current,
        pageSize: page.size
    };
    getBudgetPredictionRecordInfoList(param);
}

const onPageChange = (e) => {
    page.current = e.page;
    page.size = e.limit;
    let param = {
        param: {
            ...form
        },
        pageNum: page.current,
        pageSize: page.size
    };
    getBudgetPredictionRecordInfoList(param);
}

const exportList = ref([]);
const handleSelectionChange = (e) => {
    exportList.value = e;
}

const onExport = () => {
    exportApi.getBudgetPredictionRecordInfoListLeadingOut(form).then(res=>{
        if(res){
            exportExcelFile(res,'预测汇总表');
        }
    });
}

const visible = ref(false);
// 新增预算api
const addBudgetGatherRecord = (param) => {
    budgetManagement.addBudgetGatherRecord(param).then(res=>{
        if(res.code === '200'){
            visible.value = false;
            ElMessage.success('新增预算成功!');
        }
    });
}

// 新增预算/确认新增预算
const budgetFormRef1 = ref(null);
const budgetFormRef2 = ref(null);
const onConfirm = async () => {
    await budgetFormRef1.value.validate();
    if(budgetForm.list.length===0){
        ElMessage.warning('预算科目明细不能为空！');
        return;
    }
    await budgetFormRef2.value.validate();
    addBudgetGatherRecord(budgetForm);
}

const budgetList = ref([]);
const budgetHandleSelectionChange = (e) => {
    budgetList.value = e;
}

// 编辑
const onEdit = (row) => {
    row.isEdit = true;
}

const onCancel = (row) => {
    row.isEdit = false;
}

const updateBudgetPredictionRecord = (param,callback) => {
    budgetManagement.updateBudgetPredictionRecord(param).then(res=>{
        if(res.code === '200'){
            if(callback)callback();
        }
    });
}

const onSave = (row) => {
    updateBudgetPredictionRecord({
        budgetPredictionRecordId:row.budgetPredictionRecordId,
        cost:row.cost,
        income:row.income,
        fee:row.fee,
        profit:row.profit
    },()=>{
        row.isEdit = false;
        ElMessage.success('保存成功!');
    });
}

const addHandle = () => {
    budgetForm.list.push({
        uuid:new Date().getTime(),
        budgetSubjectId:'',
        budgetAmount:''
    });
}

const reduceHandle = () => {
    if(budgetList.value.length===0){
        ElMessage.warning('请选择要操作的行!')
        return;
    }
    budgetList.value.forEach(item=>{
        budgetForm.list.forEach((val,index)=>{
            if(item.uuid === val.uuid){
                budgetForm.list.splice(index,1);
            }
        });
    });
}

const budgetSubjectTypeList = ref([]);
const getBudgetSubjectType = (type) => {
    return  budgetManagement.getBudgetSubjectType(type).then(res=>{
        if(res.code === '200'){
            budgetSubjectTypeList.value = res.data;
        }
    });
}

const props = {
    lazy: true,
    emitPath:false,
    async lazyLoad(node, resolve) {
        const { level } = node;
        if(level === 0){
            let nodes = [
                {
                    value: 1,
                    label: '收入',
                    leaf: level >= 1,
                },
                {
                    value: 2,
                    label: '成本',
                    leaf: level >= 1,
                },
                {
                    value: 3,
                    label: '费用',
                    leaf: level >= 1,
                },
                {
                    value: 4,
                    label: '收益',
                    leaf: level >= 1,
                },
            ];
            resolve(nodes);
        }
        if(level > 0 && level < 2){
            let nodes = [];
            await getBudgetSubjectType(node.value);
            budgetSubjectTypeList.value.forEach(item=>{
                nodes.push({
                    value: item.subjectId,
                    label: item.subjectName,
                    leaf: level >= 1,
                });
            });
            resolve(nodes);
        }
    }
}

const predictionForm = reactive({
    departmentId:'',
    year: '',
    quarter: '',
    monthly: '',
    projectId:'',
    cost: '',
    income: '',
    fee: '',
    profit: '',
});


const predictionRules = reactive({
    departmentId: [{ required: true, message: '部门,不能为空!', trigger: 'change' },],
    year: [{ required: true, message: '年度,不能为空!', trigger: 'change' },],
    quarter: [{ required: true, message: '季度,不能为空!', trigger: 'change' },],
    monthly: [{ required: true, message: '月度,不能为空!', trigger: 'change' },],
    projectId: [{ required: true, message: '项目,不能为空!', trigger: 'change' },],
    cost: [{ required: true, message: '成本预算金额,不能为空!', trigger: 'change' },],
    income: [{ required: true, message: '收入预算金额,不能为空!', trigger: 'change' },],
    fee: [{ required: true, message: '费用预算金额,不能为空!', trigger: 'change' },],
    profit: [{ required: true, message: '收益预算金额,不能为空!', trigger: 'change' },],
});


// 新增预测
const predictionVisible = ref(false);
const addBudgetPredictionRecord = (param) => {
    budgetManagement.addBudgetPredictionRecord(param).then(res=>{
        if(res.code === '200'){
            predictionVisible.value = false;
            ElMessage.success('新增预测成功!');
        }
    });
}

const predictionFormRef1 = ref(null);
// 新增预测
const onPredictionConfirm =async () => {
    await predictionFormRef1.value.validate();
    addBudgetPredictionRecord(predictionForm);
}


onMounted(()=>{
    getDepartmentVo();
    getProjectList();
    getBudgetPredictionRecordInfoList({
        pageNum: 1,
        pageSize: 10
    });
});
</script>

<style lang="scss" scoped>
.budgetTabelPagePage{
  .search-wrap{
    .search-item{
      .el-input{
        width: auto !important;
      }
    }
    .search-buttons{
      .icon-export{
        width: 18px;
        height: 18px;
      }
    }
  }
}
.public-dialog-content{
  .details-box{
    span{
      font-size: 15px;
      font-weight: 600;
    }
    .buttons-box{
      .icon{
        cursor: pointer;
        width: 28px;
        height: 28px;
      }
    }
  }
}
</style>
